#!/bin/sh

# Copyright (c) 2010, Andrew "IceD" Kirilenko
# All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the COPYING file.

CAT="/bin/cat"
GREP="/bin/grep"
AWK="/bin/awk"
MKDIR="/bin/mkdir"
RMDIR="/bin/rmdir"
MOUNT="/bin/mount"
UMOUNT="/bin/umount"
NTFS3G="/bin/ntfs-3g"

mount_general () {
	devname=$1
	label=$2

	$MOUNT -o rw "$devname" "/media/$label"
}

mount_ntfs () {
	devname=$1
	label=$2

	if [ -x $NTFS3G ]; then
		$NTFS3G "$devname" "/media/$label"
	else
		mount_general "$devname" "$label"
	fi
}

mount_vfat () {
	devname=$1
	label=$2

	$MOUNT -o rw,noexec,dmask=000,fmask=111 "$devname" "/media/$label"
}

mount_any () {
	fs_type=$1
	devname=$2
	label=$3

	case "$fs_type" in
		ntfs)
			mount_ntfs "$devname" "$label"
			;;
		vfat)
			mount_vfat "$devname" "$label"
			;;
		*)
			mount_general "$devname" "$label"
			;;
	esac
}

purge_empty_dirs () {
	$RMDIR /media/*
}

# main script

[ -z "$ACTION" ] && exit

purge_empty_dirs

if [ "$ACTION" = "add" ]; then
	$CAT /etc/mtab | $GREP "^$DEVNAME " && exit

	LABEL=$ID_FS_LABEL
	if [ -z "$LABEL" ]; then
		LABEL=$ID_VENDOR
	fi
	if [ -z "$LABEL" ]; then
		LABEL="disk"
	fi

	if [ -e "/media/$LABEL" ]; then
		SUFFIX=1
		while [ -e "/media/$LABEL-$SUFFIX" ]; do
			SUFFIX=$[SUFFIX+1]
		done
		LABEL="$LABEL-$SUFFIX"
	fi

	$MKDIR -p "/media/$LABEL"
	mount_any "$ID_FS_TYPE" "$DEVNAME" "$LABEL"
	purge_empty_dirs
fi

if [ $ACTION = "remove" ]; then
	$CAT /etc/mtab | $GREP "^$DEVNAME " | $AWK '{ print $2 }' | $GREP "^/media/" || exit

	$UMOUNT -l "$DEVNAME"
	purge_empty_dirs
fi
